package com.ptswitch.material.pages.zip;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;

import com.ptswitch.material.model.base.Upload;
import com.ptswitch.material.model.material.Bom;
import com.ptswitch.material.model.material.Material;
import com.ptswitch.material.pages.base.MaterialBasePage;
import com.ptswitch.material.pages.material.ListMaterial;
import com.ptswitch.material.service.BomService;
import com.ptswitch.material.service.MaterialExcelService;
import com.ptswitch.material.service.MaterialService;
import com.ptswitch.material.util.HlogConstants;

public class ImportZip extends MaterialBasePage {
    @Inject
    private MaterialExcelService excelSer;
    @Inject
    private MaterialService materialSer;
    @Inject
    private BomService bomSer;
    @Property
    private UploadedFile file;
    @InjectPage
    private ListMaterial listMaterial;

    @OnEvent(value = EventConstants.SUCCESS)
    Object importZip() {
        checkUserIsAdmin();
        Upload upload = getWebUtil().upload(file, Upload.class);
        List<Material> materials = new ArrayList<Material>();
        List<Bom> boms = new ArrayList<Bom>();
        excelSer.buildDataFromZip(materials, boms, getWebUtil().getSavePath() + upload.getClass().getSimpleName() + "/", upload.getFilePath());
        materialSer.saveAll(materials);
        for (Bom bom : boms) {
            bomSer.saveEx(bom);
        }
        hlog(HlogConstants.updateSystem);
        return listMaterial;
    }
}
